import { createWebHistory, createRouter } from "vue-router";
import { useAuthorizationStore } from "@/stores/authorization";
import routes from "@/router/router.js";
import { ElMessage } from "element-plus";

const router = createRouter({
  history: createWebHistory(),
  routes: routes,
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 };
  },
});

router.beforeEach((to, from, next) => {
  const authorizationStore = useAuthorizationStore();
  const authorization = authorizationStore.authorization;

  if (to.path === "/") {
    next();
  } else {
    if (to.path === "/login") {
      if (authorization) {
        next("/about");
      } else {
        next();
      }
    } else if (authorization) {
      next();
    } else {
      next("/login");
      ElMessage({
        message: "请先登录哦！",
        type: "error",
      });
    }
  }
});

export default router;
